<template>
  <div class="generationPPT">

    <div class="header">
      <SvgIcon name="返回" :size="20" @click="back" />
      <span>编辑出差报告</span>
      <!-- <van-button v-if="downPPtLoading" class="button" @click="downloadPPT" type="primary">下载</van-button> -->
      <van-button v-if="true" class="button" @click="downloadPPT" type="primary">下载</van-button>
    </div>
    <!-- <van-loading v-if="loading" size="24px">加载中...</van-loading> -->
    <div class="card">
      <p class="message">
        我已为您生成了主题为‘{{ pptstr }}’的ppt纲要，请查看以下内容，您可以点击下方编辑纲要，在确定纲要内容后点击‘生成PPT’按钮、选择PPT模版即可下载完整的PPT。
      </p>
      <div class="content">
        <div class="h1">PPT标题： {{ list.topic }}</div>
        <div class="page" v-for="item, index in list.pages">
          <div class="h2" v-if="activeInput !== index + ''" @click="pageClick(index)">页面 {{ index + 1 }} ：{{
            item.title }}</div>
          <div class="h2-input" v-else>
            <van-field @blur="activeInput = ''" v-model="item.title" @keyup.enter="activeInput = ''">
              <template #label>
                <van-popover :offset="[70, 18]" :show-arrow="false" v-model:show="alert">
                  <div class="popover-item" v-for="ele in actions1" @click="onSelect(ele.text, index, -1)">
                    <SvgIcon :name="ele.icon" :style="(ele.icon === '删除' ? 'color: red;' : '') + 'margin-right:10px;'"
                      :size="16" /><span>{{
                        ele.text
                      }}</span>
                  </div>
                  <template #reference>
                    <SvgIcon name="更多" @click="alert = true" :size="20" />
                  </template>
                </van-popover>

              </template>
            </van-field>
          </div>
          <ul class="row">
            <li v-for="ite, ind in item.paragraphs">
              <div class="h3" v-if="activeInput !== index + '-' + ind" @click="rowClick(index, ind)">
                {{ ite.title }}：{{ ite.content }}
              </div>
              <div class="h2-input" v-else>
                <van-field v-model="ite.title" @keyup.enter="activeInput = ''">
                  <template #label>
                    <van-popover :offset="[70, 18]" :show-arrow="false" v-model:show="alert">
                      <div class="popover-item" v-for="ele in actions2" @click="onSelect(ele.text, index, ind)"
                        v-on:blur="alert = false">
                        <SvgIcon :name="ele.icon"
                          :style="(ele.icon === '删除' ? 'color: red;' : '') + 'margin-right:10px;'" :size="16" /><span>{{
                            ele.text
                          }}</span>
                      </div>
                      <template #reference>
                        <SvgIcon name="更多" @click="alert = true" :size="20" />
                      </template>
                    </van-popover>

                  </template>
                </van-field>
                <van-field @blur="activeInput = ''" style="padding-left: 5px;margin-top: 5px;" v-model="ite.content"
                  @keyup.enter="activeInput = ''">
                </van-field>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <van-overlay :show="loading">
      <van-loading v-if="loadingContent === '生成中...'" color="#1989fa" size="24"
        style="position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);">
        <span>
          {{ loadingContent }}
        </span>
      </van-loading>
      <van-circle v-else v-model:current-rate="currentRate" :rate="0" :speed="100" :text="text" />
    </van-overlay>
    <van-notify type="success">
      <van-icon name="bell" style="margin-right: 4px;" />
      <span>PPT生成失败</span>
    </van-notify>

  </div>
</template>

<script setup>
import {createPPT, GeneratePPT, GenerateReportFilePath} from "@/api/index"
import { useRouter, useRoute } from 'vue-router';
import { ref, reactive, onMounted, computed } from "vue"
import { showNotify } from 'vant';

import SvgIcon from '@/components/SvgIcon.vue';
const router = useRouter()
const route = useRoute()
const list = ref({})
const loading = ref(false)
const downPPtLoading = ref(false)
const loadingContent = ref("")
const currentRate = ref(0)
const pptstr = ref(route.query.message)
const activeInput = ref('')
const text = computed(() => currentRate.value.toFixed(0) + '%');
let alert = ref('')
const actions1 = ref([
  { text: '在上方添加一页', icon: '上方添加一页' },
  { text: '在下方添加一页', icon: '下方添加一页' },
  { text: '删除此页', icon: '删除' },
]);
const actions2 = ref([
  { text: '在上方添加一项', icon: '上方添加一页' },
  { text: '在下方添加一项', icon: '下方添加一页' },
  { text: '删除此项', icon: '删除' },
]);
const pageClick = (index) => {
  activeInput.value = index + ''
  alert = false
}
const rowClick = (index, ind) => {
  activeInput.value = index + '-' + ind
  alert = false

}
const onSelect = (data, index, ind) => {
  const row = {
    title: '项',
    content: ind + 2
  }
  const page = {
    title: '',
    paragraphs: [
      {
        title: '项',
        content: 1
      },
      {
        title: '项',
        content: 2
      },
      {
        title: '项',
        content: 3
      },
    ]
  }
  const dataobj = {
    "在上方添加一页": () => {
      list.value.pages.splice(index, 0, page)
    },
    "在下方添加一页": () => {
      list.value.pages.splice(index + 1, 0, page)

    },
    "在上方添加一项": () => {
      list.value.pages[index].paragraphs.splice(ind, 0, row)

    },
    "在下方添加一项": () => {
      list.value.pages[index].paragraphs.splice(ind + 1, 0, row)

    },
    "删除此页": () => {
      list.value.pages.splice(index, 1)

    },
    "删除此项": () => {
      list.value.pages[index].paragraphs.splice(ind, 1)

    },
  }
  dataobj[data]()
  alert = false

}
const downloadPPT = async () => {

  if(isAndroidWebView()){
    loading.value = true
    loadingContent.value = '下载中...'
    var fileList = []
    if (route.query.filePaths != undefined && route.query.filePaths != '') {
      fileList = route.query.filePaths.split(",")
    }
    const data = await GenerateReportFilePath({
      ppt: JSON.stringify(list.value),
      filePaths: fileList,
    }, currentRate)
    loading.value = false
    let url = data.data;
    AndroidInterface.downloadFile(url);
  }else {
    try {
      loading.value = true
      loadingContent.value = '下载中...'
      var fileList = []
      if (route.query.filePaths != undefined && route.query.filePaths != '') {
        fileList = route.query.filePaths.split(",")
      }
      const data = await GeneratePPT({
        ppt: JSON.stringify(list.value),
        filePaths: fileList,
      }, currentRate)
      console.log('data', data)

      // 创建 Blob 对象
      const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'});
      // 创建指向该 Blob 的 URL
      const url = window.URL.createObjectURL(blob);
      // 创建 a 元素用于下载
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'topic.pptx'); // 设置下载文件名
      document.body.appendChild(link);
      link.click(); // 模拟点击以触发下载
      document.body.removeChild(link); // 下载后移除元素
      window.URL.revokeObjectURL(url); // 释放 URL 对象
      loading.value = false
    } catch (error) {
      console.error('下载文件出错:', error);
      loading.value = false
    }
  }
}


const isAndroidWebView = () => {
  return /Android/.test(navigator.userAgent) && /wv/.test(navigator.userAgent);
}
const initPPT = async () => {
  if (!pptstr.value) return
  loading.value = true
  loadingContent.value = '生成中...'
  downPPtLoading.value = false
  var fileList = []
  //测试数据
  // list.value = JSON.parse("{\"topic\":\"关于上课玩手机检讨\",\"pages\":[{\"title\":\"引言\",\"paragraphs\":[{\"title\":\"引言\",\"content\":\"本文旨在探讨上课玩手机的检讨，分析其对学习的影响，以及如何避免上课玩手机。\"}]},{\"title\":\"上课玩手机的原因\",\"paragraphs\":[{\"title\":\"缺乏学习动力\",\"content\":\"学生可能因为缺乏学习动力而上课玩手机。\"}]},{\"title\":\"上课玩手机的影响\",\"paragraphs\":[{\"title\":\"影响注意力集中\",\"content\":\"上课玩手机会分散学生的注意力，影响学习效果。\"}]},{\"title\":\"如何避免上课玩手机\",\"paragraphs\":[{\"title\":\"设定学习目标\",\"content\":\"设定明确的学习目标可以帮助学生集中注意力，避免上课玩手机。\"}]},{\"title\":\"结论\",\"paragraphs\":[{\"title\":\"结论\",\"content\":\"上课玩手机不仅影响学习效果，还可能对学生的身心健康造成影响。因此，我们需要采取措施来避免上课玩手机。\"}]},{\"title\":\"参考文献\",\"paragraphs\":[{\"title\":\"参考文献\",\"content\":\"本文参考了以下文献：[1]，[2]，[3]。\"}]}]}")
  try {
    if (route.query.filePaths != undefined && route.query.filePaths != '') {
      fileList = route.query.filePaths.split(",")
    }
    const { data, code } = await createPPT({
      topic: pptstr.value,
      filePaths: fileList,
    });
    if (code === 200 && data) {
      list.value = JSON.parse(data);
      downPPtLoading.value = true
      console.log(list.value);
    } else {
      // 处理非200响应的情况
      console.error('Failed to get PPT:', code);
    }
  } catch (error) {
    // 记录错误信息
    showNotify({ type: 'danger', message: 'PPT生成失败' });
    console.error('Error fetching PPT:', error);
  } finally {
    // 确保loading状态被正确更新
    loading.value = false;
  }


}
const BodyClick = (e) => {
  //# top
  const arr = ['h2', 'h3', 'van-field__control']
  e.preventDefault()
  console.dir(e.target.href)
  if (e.target.innerHTML.toString().includes('更多') || e.target?.href?.animVal.includes('更多')) return
  if (!arr.includes(e.target.classList[0])) {
    activeInput.value = ''
  }
}
const addBodyBlur = () => {
  document.body.addEventListener('click', BodyClick)
}
onMounted(() => {
  // addBodyBlur()
  initPPT()
})
const back = () => {
  router.push('/ppt')
}
</script>

<style lang="scss" scoped>
.generationPPT {
  width: 100%;
  height: 100%;
  padding: 1px 16px;
  background-color: #f5f5f5;
  overflow: auto;

  .header {
    display: flex;
    font-size: 16px;
    align-items: center;
    color: #191919;

    text-align: center;
    font-weight: 500;
    margin-top: 10px;

    span {
      margin: 0 5px;
    }

    .button {
      width: 80px;
      height: 32px;
      margin-left: auto;

    }
  }

  .card {
    width: 100%;
    background-color: #fff;
    padding: 16px;
    border-radius: 6px;
    margin-top: 30px;

    .message {
      color: #1F2328;
      font-size: 14px;
    }

    .content {
      width: 100%;
      border-radius: 6px;
      background: #F6F6F6;
      padding-top: 8px;
      padding-bottom: 8px;
      margin-top: 8px;

      .h1 {
        color: #191919;
        font-size: 14px;
        font-weight: 600;
        width: 100%;
        padding: 0 8px 0 28px;
      }

      .page {
        color: #191919;
        font-family: "Microsoft YaHei";
        font-size: 14px;
        font-weight: 600;
        margin: 16px 0;

        .h2 {
          padding: 0 8px 0 28px;
        }

        .h2-input {
          display: flex;
          align-items: center;
          flex-wrap: wrap;

          :deep(.van-field) {
            align-items: center;
            padding: 0;
            background-color: transparent;
            border-radius: 4px;
            border: 1px solid var(--van-primary-color);
            background: #E0E9FF;
            height: 40px;

            .van-field__label {
              width: 20px;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }


        }

        ul {
          list-style: disc;
          padding-left: 45px;
          color: #191919;
          font-size: 14px;
          font-weight: 400;
          margin-top: 8px;
          width: 100%;

          li {
            width: 100%;
            margin: 16px 0;
            padding-right: 10px;
          }
        }
      }
    }
  }

}

:deep(.van-popover__action) {
  width: 160px !important;


}

:deep(.van-popover__content) {
  width: 160px !important;

  .popover-item {
    margin: 16px 0;
    padding: 0 16px;
    display: flex;
    color: #1F2328;
    font-size: 14px;
  }
}

.van-loading {
  width: 100%;
  display: flex;
  height: 100%;
  flex-wrap: wrap;
  align-content: center;
  justify-content: center;
}

:deep(.van-circle) {
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
